﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>

#include <QNetworkInterface>
#include <QBuffer>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_webSvr = new QWebSocketServer(QStringLiteral("Echo Server"),QWebSocketServer::NonSecureMode, this);
    m_webSvr->listen(QHostAddress::Any,9000);
    connect(m_webSvr, &QWebSocketServer::newConnection,this, &MainWindow::onNewConnection);
    connect(m_webSvr, &QWebSocketServer::closed, this, &MainWindow::closed);
    m_webClient = NULL;
    //
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("../../config.db");
    if(m_db.open())
    {
        m_dbquery = new QSqlQuery(m_db);
    }
    else
    {
        qDebug() << QString("db open fail error=%1").arg(m_db.lastError().text());
    }

//    QList<QNetworkInterface>  NetList;
//    int NetCount = 0;
//    int Neti = 0;
//    QNetworkInterface thisNet;
//    NetList = QNetworkInterface::allInterfaces();
//    NetCount = NetList.count();
//    for(Neti = 0;Neti < NetCount; Neti++)
//    {
//        if(NetList[Neti].isValid())
//        {
//            thisNet = NetList[Neti];
//            break;
//        }
//    }
//    QString mac = thisNet.hardwareAddress();
//    qDebug() << mac;
    //
    //QList是指向元素内存的指针数组,所以可以随机访问
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    qint32 nCnt=nets.count();
    QString strMacAddr = "";
    qDebug() << nCnt;
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets.at(i).flags().testFlag(QNetworkInterface::IsUp)
                && nets.at(i).flags().testFlag(QNetworkInterface::IsRunning)
                && !nets.at(i).flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets.at(i).hardwareAddress();
            qDebug() << "dddd=" << strMacAddr;
//            break;
        }
    }

    //
    initNetComm();
}

MainWindow::~MainWindow()
{
    m_webSvr->close();
    if(NULL != m_dbquery)
    {
        m_db.close();
        delete m_dbquery;
        m_dbquery = NULL;
    }
    delete ui;
}

void MainWindow::onNewConnection()
{
    if(NULL != m_webClient)
    {
        m_webClient->deleteLater();
        m_webClient = NULL;
    }
    if(NULL == m_webClient)
    {
        m_webClient = m_webSvr->nextPendingConnection();
        connect(m_webClient, &QWebSocket::textMessageReceived, this, &MainWindow::processTextMessage);
        connect(m_webClient, &QWebSocket::binaryMessageReceived, this, &MainWindow::processBinaryMessage);
        connect(m_webClient, &QWebSocket::disconnected, this, &MainWindow::socketDisconnected);
    }
    qDebug() << "new connect";
}

void MainWindow::closed()
{
    qDebug() << "closed";
}

QByteArray MainWindow::jsonobjToByteArray(QJsonObject obj, const QString &key)
{
    QByteArray szJsonToBa="";
    if(obj.contains(key))
    {
        QJsonValue value = obj.take(key);
        if(value.isString())
        {
            szJsonToBa = value.toString().toUtf8();
        }
    }
    return szJsonToBa;
}

bool MainWindow::jsonobjTobool(QJsonObject obj, const QString &key)
{
    bool bet = false;
    if(obj.contains(key))
    {
        QJsonValue value = obj.take(key);
        if(value.isBool())
            bet = value.toBool();
    }
    return bet;
}

int MainWindow::jsonobjToint(QJsonObject obj, const QString &key)
{
    if(obj.contains(key))
    {
        QJsonValue value = obj.take(key);
        return value.toInt();
    }
    return 0;
}

void MainWindow::queryUserServiceCfg(QString &szcmd)
{
    m_szLog = QString("select * from t_userServiceCfg");
    if(m_dbquery->exec(m_szLog))
    {
        int nuserTypeIndex = m_dbquery->record().indexOf("userType");
        int nuserDescIndex = m_dbquery->record().indexOf("userDesc");
        int nhotelAdvertisingIndex = m_dbquery->record().indexOf("hotelAdvertising");
        int nexperience1Index = m_dbquery->record().indexOf("experience1");
        int npSignIndex = m_dbquery->record().indexOf("pSign");
        int npSignVipRiteIndex = m_dbquery->record().indexOf("pSignVipRite");
        int npPublicityIndex = m_dbquery->record().indexOf("pPublicity");
        int npAdvisoryIndex = m_dbquery->record().indexOf("pAdvisory");
        int npDirectingIndex = m_dbquery->record().indexOf("pDirecting");
        int npStatisticsIndex = m_dbquery->record().indexOf("pStatistics");
        int nexperience2Index = m_dbquery->record().indexOf("experience2");
        int nmSignIndex = m_dbquery->record().indexOf("mSign");
        int nmPublicityIndex = m_dbquery->record().indexOf("mPublicity");
        int nmAdvisoryIndex = m_dbquery->record().indexOf("mAdvisory");
        int nmDirectingIndex = m_dbquery->record().indexOf("mDirecting");
        int nmStatisticsIndex = m_dbquery->record().indexOf("mStatistics");
        int nmSameOneIndex = m_dbquery->record().indexOf("mSameOne");
        QJsonObject JsonMsg;
        JsonMsg.insert("cmd", szcmd);
        QJsonArray JsonArray;
        while(m_dbquery->next())
        {
            int userType = m_dbquery->value(nuserTypeIndex).toInt();
            QString userDesc = m_dbquery->value(nuserDescIndex).toString();
            bool hotelAdvertising = m_dbquery->value(nhotelAdvertisingIndex).toBool();
            bool experience1 = m_dbquery->value(nexperience1Index).toBool();
            QString pSign = m_dbquery->value(npSignIndex).toString();
            bool pSignVipRite = m_dbquery->value(npSignVipRiteIndex).toBool();
            bool pPublicity = m_dbquery->value(npPublicityIndex).toBool();
            bool pAdvisory = m_dbquery->value(npAdvisoryIndex).toBool();
            bool pDirecting = m_dbquery->value(npDirectingIndex).toBool();
            bool pStatistics = m_dbquery->value(npStatisticsIndex).toBool();
            bool experience2 = m_dbquery->value(nexperience2Index).toBool();
            bool mSign = m_dbquery->value(nmSignIndex).toBool();
            bool mPublicity = m_dbquery->value(nmPublicityIndex).toBool();
            bool mAdvisory = m_dbquery->value(nmAdvisoryIndex).toBool();
            bool mDirecting = m_dbquery->value(nmDirectingIndex).toBool();
            bool mStatistics = m_dbquery->value(nmStatisticsIndex).toBool();
            bool mSameOne = m_dbquery->value(nmSameOneIndex).toBool();
            //
            QJsonObject JsonObj;
            JsonObj.insert("userType", userType);
            JsonObj.insert("userDesc", userDesc);
            JsonObj.insert("hotelAdvertising", hotelAdvertising);
            JsonObj.insert("experience1", experience1);
            JsonObj.insert("pSign",pSign);
            JsonObj.insert("pSignVipRite", pSignVipRite);
            JsonObj.insert("pPublicity", pPublicity);
            JsonObj.insert("pAdvisory", pAdvisory);
            JsonObj.insert("pDirecting", pDirecting);
            JsonObj.insert("pStatistics", pStatistics);
            JsonObj.insert("experience2", experience2);
            JsonObj.insert("mSign", mSign);
            JsonObj.insert("mPublicity", mPublicity);
            JsonObj.insert("mAdvisory", mAdvisory);
            JsonObj.insert("mDirecting", mDirecting);
            JsonObj.insert("mStatistics", mStatistics);
            JsonObj.insert("mSameOne", mSameOne);
            QJsonValue jsonValue(JsonObj);
            JsonArray.push_back(jsonValue);
        }
        QJsonValue val(JsonArray);
        JsonMsg.insert("data",val);
        QJsonDocument jsonDoc;
        jsonDoc.setObject(JsonMsg);
        QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
        m_webClient->sendTextMessage(QString(byteArray).toUtf8());
    }
}

/***************************************************
cmd: "saveUserServiceCfg",
 data: [
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "全流程签到 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : "酒店高层 ",
     userType : 1
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : true,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "去拍照签到 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : " ",
     userType : 2
   },
   {
     experience1 : true,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "扫码注册签到 ",
     pSignVipRite : false,
     pStatistics : true,
     userDesc : " ",
     userType : 3
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "精简签到 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : " ",
     userType : 4
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : true,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : "黑烟游侠 ",
     userType : 5
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : "潮汐猎人 ",
     userType : 6
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : " ",
     userType : 7
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : true,
     mPublicity : false,
     mSameOne : true,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : true,
     userDesc : "骷髅 ",
     userType : 8
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : " ",
     userType : 9
   },
   {
     experience1 : false,
     experience2 : false,
     hotelAdvertising : false,
     mAdvisory : false,
     mDirecting : false,
     mPublicity : false,
     mSameOne : false,
     mSign : false,
     mStatistics : false,
     pAdvisory : false,
     pDirecting : false,
     pPublicity : false,
     pSign : "无签到模块 ",
     pSignVipRite : false,
     pStatistics : false,
     userDesc : "陌生人 ",
     userType : 10
   }
 ]
}
***************************************************/

void MainWindow::saveUserServiceCfg(QJsonObject &obj, QString &szcmd)
{
    bool bRet = false;
    if(obj.contains("data"))
    {
        QJsonValue list = obj.take("data");
        if(list.isArray())
        {
            QJsonArray array = list.toArray();
            for(int i=0; i<array.size(); i++)
            {
                //解析每个data[]中的内容
                QJsonValue everyObjVal = array.at(i);
                if(everyObjVal.isObject())
                {
                    QJsonObject eveOjb = everyObjVal.toObject();
                    int userType = jsonobjToint(eveOjb,"userType");
                    QByteArray userDesc = jsonobjToByteArray(eveOjb, "userDesc");
                    bool hotelAdvertising = jsonobjTobool(eveOjb, "hotelAdvertising");
                    bool experience1 = jsonobjTobool(eveOjb, "experience1");
                    QByteArray pSign = jsonobjToByteArray(eveOjb, "pSign");
                    bool pSignVipRite = jsonobjTobool(eveOjb, "pSignVipRite");
                    bool pPublicity = jsonobjTobool(eveOjb, "pPublicity");
                    bool pAdvisory = jsonobjTobool(eveOjb, "pAdvisory");
                    bool pDirecting = jsonobjTobool(eveOjb, "pDirecting");
                    bool pStatistics = jsonobjTobool(eveOjb, "pStatistics");
                    bool experience2 = jsonobjTobool(eveOjb, "experience2");
                    bool mSign = jsonobjTobool(eveOjb, "mSign");
                    bool mPublicity = jsonobjTobool(eveOjb, "mPublicity");
                    bool mAdvisory = jsonobjTobool(eveOjb, "mAdvisory");
                    bool mDirecting = jsonobjTobool(eveOjb, "mDirecting");
                    bool mStatistics = jsonobjTobool(eveOjb, "mStatistics");
                    bool mSameOne = jsonobjTobool(eveOjb, "mSameOne");
                    m_szLog = QString("update t_userServiceCfg set userDesc='%1',hotelAdvertising=%2,"
                                      "experience1=%3,pSign='%4',pSignVipRite=%5,pPublicity=%6,pAdvisory=%7,pDirecting=%8,"
                                      "pStatistics=%9,experience2=%10,mSign=%11,mPublicity=%12,mAdvisory=%13,"
                                      "mDirecting=%14,mStatistics=%15,mSameOne=%16 where userType = %17")
                            .arg(userDesc.data()).arg(hotelAdvertising)
                            .arg(experience1).arg(pSign.data()).arg(pSignVipRite).arg(pPublicity).arg(pAdvisory).arg(pDirecting)
                            .arg(pStatistics).arg(experience2).arg(mSign).arg(mPublicity).arg(mAdvisory)
                            .arg(mDirecting).arg(mStatistics).arg(mSameOne).arg(userType);
                    bRet = m_dbquery->exec(m_szLog);
                }
            }
        }
    }
    QString msg;
    if(bRet)
        msg = u8"数据保存成功";
    else
        msg = u8"数据保存失败，请检查！";
    QJsonObject JsonMsg;
    JsonMsg.insert("cmd", szcmd);
    JsonMsg.insert("data",msg);
    QJsonDocument jsonDoc;
    jsonDoc.setObject(JsonMsg);
    QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
    m_webClient->sendTextMessage(QString(byteArray).toUtf8());
}

void MainWindow::initNetComm()
{
    m_manager = new QNetworkAccessManager(this);
    connect(m_manager,&QNetworkAccessManager::finished,this,&MainWindow::accessManagerFinish,Qt::QueuedConnection);
}

void MainWindow::accessManagerFinish(QNetworkReply *reply)
{
    if(reply && QNetworkReply::NoError == reply->error())
    {
        int nsize = reply->bytesAvailable();
        qDebug() << nsize;
        if(reply->bytesAvailable())
            qDebug() << reply->readAll().size();
    }
    else
    {
        QString strLog = QString("http manager Error=%1,desc=%2").arg(reply->error()).arg(reply->errorString());
        qDebug() << strLog.toUtf8().data();
    }

    reply->deleteLater();
    reply = NULL;
}

void MainWindow::processTextMessage(QString message)
{
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(message.toUtf8(), &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            QJsonObject obj = parse_doucment.object();
            if(obj.contains("cmd"))
            {
                QJsonValue cmd_value = obj.take("cmd"); //cmd value
                if(cmd_value.isString())
                {
                    QString szcmd = cmd_value.toString();
                    if(QString("queryUserServiceCfg") == szcmd)
                    {
                        queryUserServiceCfg(szcmd);
                    }
                    else if(QString("saveUserServiceCfg") == szcmd)
                    {
                        saveUserServiceCfg(obj,szcmd);
                    }
                }
            }
        }
        else
        {
            qDebug() << "message is't object";
        }
    }
}

void MainWindow::processBinaryMessage(QByteArray message)
{
    qDebug() << "processBinary=" << message;
}

void MainWindow::socketDisconnected()
{
    qDebug() << "socketDisconnected";
    if(NULL != m_webClient)
    {
        m_webClient->deleteLater();
        m_webClient = NULL;
    }
}


void MainWindow::on_pushButton_clicked()
{
    m_manager->get(QNetworkRequest(QUrl("http://192.168.100.157:9000/[yoyozz.com]%E5%86%B0%E6%B2%B3%E4%B8%96%E7%BA%AA%E5%B7%A8%E8%9B%8B%E6%81%B6%E4%BD%9C%E5%89%A7.HD720P.X264.AAC.%E4%B8%AD%E8%8B%B1%E5%AD%97%E5%B9%95.YoYozz.mp4")));
}
